<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Explorer: A Categorical Compiler Architecture</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&family=Source+Serif+4:opsz,wght@8..60,400;600&display=swap" rel="stylesheet">

    <!-- Chosen Palette: Serene Academia -->
    <!-- Application Structure Plan: The SPA is designed as an interactive dashboard centered around a clickable diagram of the compiler's architecture. This non-linear, hub-and-spoke model is chosen over a linear document structure to enhance usability and exploration. Users get a high-level overview from the central diagram and then dive into thematic sections (e.g., "Categorical Toolkit," "Optimization Mapping") based on their interest. This structure allows both experts and novices to navigate the complex information effectively, fostering understanding of the system's interconnected parts. Key interactions include clicking/hovering the main diagram to populate a details panel, toggling cards in the "Toolkit" to learn concepts, and using a dropdown to dynamically update a chart that connects theory to practice. -->
    <!-- Visualization & Content Choices:
        - Report Info: Overall Compiler Architecture -> Goal: Organize/Relationships -> Viz: Interactive HTML/CSS Diagram -> Interaction: Click/Hover on IR blocks to populate a details panel -> Justification: Provides a persistent mental model and primary navigation hub. -> Library: Tailwind CSS.
        - Report Info: Core Categorical Concepts (Functors, Sheaves, etc.) -> Goal: Inform/Organize -> Viz: Grid of interactive flip cards -> Interaction: Click to reveal details -> Justification: Breaks down dense mathematical concepts into digestible, on-demand chunks. -> Library: Vanilla JS + Tailwind.
        - Report Info: Mapping Optimizations to Categorical Constructs -> Goal: Compare/Relationships -> Viz: Dynamic Bar Chart linked to text -> Interaction: Dropdown selection updates chart and associated descriptive text -> Justification: Interactively demonstrates the practical application of the theoretical constructs, making the connection explicit. -> Library: Chart.js (Canvas).
        - Report Info: Guiding Philosophy & Human-AI Symbiosis -> Goal: Inform -> Viz: Styled cards and a simple 3-step diagram -> Interaction: Static content -> Justification: Presents conceptual and narrative information in a clear, organized, and visually engaging manner. -> Library: Tailwind CSS.
    -->
    <!-- CONFIRMATION: NO SVG graphics used. NO Mermaid JS used. -->

    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f5f5f4; /* stone-100 */
            color: #292524; /* stone-800 */
        }
        h1, h2, h3 {
            font-family: 'Source Serif 4', serif;
            font-weight: 600;
        }
        .content-section {
            display: none;
        }
        .content-section.active {
            display: block;
        }
        .nav-link {
            transition: all 0.2s ease-in-out;
            cursor: pointer;
        }
        .nav-link.active {
            color: #0d9488; /* teal-600 */
            border-bottom-color: #0d9488; /* teal-600 */
        }
        .chart-container {
            position: relative;
            width: 100%;
            max-width: 700px;
            margin-left: auto;
            margin-right: auto;
            height: 350px;
            max-height: 50vh;
        }
        .arch-box {
            transition: all 0.3s ease-in-out;
            cursor: pointer;
        }
        .arch-box:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
        }
        .arch-box.selected {
            border-color: #0d9488;
            box-shadow: 0 0 0 3px rgba(13, 148, 136, 0.3);
        }
        .toolkit-card-back {
            transform: rotateY(180deg);
        }
        .toolkit-card.is-flipped .toolkit-card-inner {
            transform: rotateY(180deg);
        }
        .toolkit-card-inner {
            transition: transform 0.6s;
            transform-style: preserve-3d;
        }
        .toolkit-card-front, .toolkit-card-back {
            -webkit-backface-visibility: hidden;
            backface-visibility: hidden;
        }
    </style>
</head>
<body class="antialiased">

    <div class="container mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl">

        <header class="py-8 text-center border-b border-stone-200">
            <h1 class="text-4xl md:text-5xl font-bold text-stone-900">A Categorical Compiler Architecture</h1>
            <p class="mt-4 text-lg text-stone-600">An interactive exploration of a functorial and Grothendieck-inspired compiler design.</p>
        </header>

        <nav class="sticky top-0 bg-stone-100/80 backdrop-blur-md z-10 border-b border-stone-200 my-8">
            <ul class="flex items-center justify-center flex-wrap gap-x-4 gap-y-2 md:gap-x-8 text-sm md:text-base font-medium text-stone-500 py-3">
                <li><a class="nav-link border-b-2 border-transparent hover:text-teal-600 hover:border-teal-600 py-2" data-target="overview">Architecture</a></li>
                <li><a class="nav-link border-b-2 border-transparent hover:text-teal-600 hover:border-teal-600 py-2" data-target="toolkit">Categorical Toolkit</a></li>
                <li><a class="nav-link border-b-2 border-transparent hover:text-teal-600 hover:border-teal-600 py-2" data-target="optimizations">Optimization Mapping</a></li>
                <li><a class="nav-link border-b-2 border-transparent hover:text-teal-600 hover:border-teal-600 py-2" data-target="philosophy">Foundations</a></li>
                <li><a class="nav-link border-b-2 border-transparent hover:text-teal-600 hover:border-teal-600 py-2" data-target="symbiosis">Human-AI Symbiosis</a></li>
            </ul>
        </nav>

        <main id="main-content">

            <!-- SECTION: ARCHITECTURE OVERVIEW -->
            <section id="overview" class="content-section">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold text-stone-800">Compiler Flow Overview</h2>
                    <p class="mt-4 max-w-3xl mx-auto text-stone-600">
                        This application visualizes a compiler designed with deep mathematical principles. Its core is a two-layer system that translates human ideas into optimized machine code. The **Semantic Layer** captures the "what," and the **Execution Layer** defines the "how." Each block below represents a distinct Intermediate Representation (IR), a step in the compilation journey. Click or hover on any block to learn more about its role.
                    </p>
                </div>

                <div class="flex flex-col lg:flex-row gap-8 items-start">
                    <!-- Details Panel -->
                    <div class="w-full lg:w-1/3 p-6 bg-white rounded-2xl shadow-lg sticky lg:top-32">
                        <h3 id="details-title" class="text-2xl font-bold text-teal-700">Select a Component</h3>
                        <p id="details-text" class="mt-3 text-stone-600">Hover over or click on a component in the main diagram to see its description and key categorical concepts here.</p>
                        <div id="details-extra" class="mt-4 text-sm text-stone-500 bg-stone-50 p-3 rounded-md"></div>
                    </div>

                    <!-- Architecture Diagram -->
                    <div class="w-full lg:w-2/3">
                        <div class="space-y-6">
                            <!-- Semantic Layer -->
                            <div class="p-6 bg-teal-50/50 border-2 border-teal-200 rounded-2xl">
                                <h3 class="text-2xl font-semibold mb-4 text-center text-teal-800">Semantic Layer (Human-Centric)</h3>
                                <div class="relative grid grid-cols-1 md:grid-cols-3 gap-4 p-4 items-center">
                                     <div class="arch-box relative z-10 p-4 bg-white rounded-xl shadow-md border text-center" data-id="HLI">
                                        <h4 class="font-semibold">High-Level Intent IR</h4>
                                    </div>
                                    <div class="arch-box relative z-10 p-4 bg-white rounded-xl shadow-md border text-center" data-id="DSI">
                                        <h4 class="font-semibold">Domain-Specific Intent IR</h4>
                                    </div>
                                    <div class="arch-box relative z-10 p-4 bg-white rounded-xl shadow-md border text-center" data-id="LSLI">
                                        <h4 class="font-semibold">Low-Level Scheduling Intent IR</h4>
                                    </div>
                                </div>
                            </div>

                            <div class="flex justify-center items-center py-4">
                                <span class="text-stone-500 font-semibold text-lg mx-4 text-center">↓ Bidirectional Profunctorial Mapping ↓</span>
                            </div>

                            <!-- Execution Layer -->
                            <div class="p-6 bg-indigo-50/50 border-2 border-indigo-200 rounded-2xl">
                                <h3 class="text-2xl font-semibold mb-4 text-center text-indigo-800">Execution Layer (Machine-Centric)</h3>
                                <div class="relative grid grid-cols-1 md:grid-cols-3 gap-4 p-4 items-center">
                                    <div class="arch-box relative z-10 p-4 bg-white rounded-xl shadow-md border text-center" data-id="HLE">
                                        <h4 class="font-semibold">High-Level Execution IR</h4>
                                    </div>
                                    <div class="arch-box relative z-10 p-4 bg-white rounded-xl shadow-md border text-center" data-id="DSE">
                                        <h4 class="font-semibold">Domain-Specific Execution IR</h4>
                                    </div>
                                    <div class="arch-box relative z-10 p-4 bg-white rounded-xl shadow-md border text-center" data-id="LLM_IR">
                                        <h4 class="font-semibold">Low-Level Machine IR</h4>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- SECTION: CATEGORICAL TOOLKIT -->
            <section id="toolkit" class="content-section">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold text-stone-800">The Categorical Toolkit</h2>
                    <p class="mt-4 max-w-3xl mx-auto text-stone-600">
                        Category theory provides the mathematical language for this compiler's design. It is a "theory of everything" for systems and processes. Below are the core concepts used in this architecture. Click on any card to flip it over and learn about its specific role.
                    </p>
                </div>
                <div id="toolkit-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <!-- Populated by JS -->
                </div>
            </section>

            <!-- SECTION: OPTIMIZATIONS -->
            <section id="optimizations" class="content-section">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold text-stone-800">Mapping Optimizations to Categories</h2>
                    <p class="mt-4 max-w-3xl mx-auto text-stone-600">
                        A key goal of this architecture is to formally describe common compiler optimizations using categorical constructs. This moves optimization from an ad-hoc art to a verifiable science. Select an optimization from the dropdown to see which categorical tools are most relevant for its implementation.
                    </p>
                </div>

                <div class="flex flex-col lg:flex-row gap-8 items-start p-6 bg-white rounded-2xl shadow-lg">
                    <div class="w-full lg:w-1/2">
                        <label for="optimization-selector" class="block text-sm font-medium text-stone-700">Select an Optimization:</label>
                        <select id="optimization-selector" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-stone-300 focus:outline-none focus:ring-teal-500 focus:border-teal-500 sm:text-sm rounded-md">
                            <!-- Populated by JS -->
                        </select>
                        <div id="optimization-details" class="mt-6">
                            <h3 id="opt-title" class="text-xl font-bold text-stone-800"></h3>
                            <p id="opt-desc" class="mt-2 text-stone-600"></p>
                            <div class="mt-4 bg-stone-50 p-4 rounded-md border border-stone-200">
                                <h4 class="font-semibold text-stone-700">Categorical Rationale</h4>
                                <p id="opt-rationale" class="mt-1 text-sm text-stone-600"></p>
                            </div>
                        </div>
                    </div>
                    <div class="w-full lg:w-1/2 flex flex-col items-center">
                        <h4 class="text-lg font-semibold text-stone-700 mb-2">Conceptual Relevance</h4>
                        <div class="chart-container">
                            <canvas id="optimizationChart"></canvas>
                        </div>
                    </div>
                </div>
            </section>

            <!-- SECTION: PHILOSOPHY -->
            <section id="philosophy" class="content-section">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold text-stone-800">Guiding Philosophy: A Council of Luminaries</h2>
                     <p class="mt-4 max-w-3xl mx-auto text-stone-600">
                        The design is not arbitrary; it's guided by the insights of pioneers in computer science, mathematics, and physics. Their philosophies converge on the pursuit of simplicity, structural integrity, and verifiable correctness through principled abstraction.
                    </p>
                </div>
                <div id="philosophy-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                     <!-- Populated by JS -->
                </div>
            </section>

             <!-- SECTION: SYMBIOSIS -->
            <section id="symbiosis" class="content-section">
                <div class="text-center mb-12">
                    <h2 class="text-3xl font-bold text-stone-800">Human-AI Symbiosis</h2>
                    <p class="mt-4 max-w-3xl mx-auto text-stone-600">
                        A novel component of this architecture is the Metacircular Evaluator, a collaboration between a human developer and a Large Language Model (LLM). This partnership is designed to navigate complex or undecidable problems by making strategic choices that are then validated by the compiler's formal system.
                    </p>
                </div>

                <div class="bg-white p-8 rounded-2xl shadow-lg">
                    <h3 class="text-2xl font-bold text-stone-800 text-center">The Axiom of Constrained Choice</h3>
                    <p class="mt-3 text-stone-600 text-center max-w-2xl mx-auto">
                        Many compiler problems, like finding the absolute best optimization strategy, are undecidable. Instead of relying purely on heuristics, this model introduces a guided choice mechanism.
                    </p>
                    <div class="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6 text-center relative">
                        <div class="absolute top-1/2 left-0 w-full h-0.5 bg-stone-300 hidden md:block z-0"></div>
                        <div class="relative z-10 p-4 bg-white">
                            <div class="flex items-center justify-center w-16 h-16 mx-auto bg-teal-100 text-teal-700 rounded-full text-2xl font-bold mb-3">1</div>
                            <h4 class="font-bold text-lg">Propose</h4>
                            <p class="text-sm text-stone-600">At a decision point, the LLM proposes a set of potential transformations or solutions.</p>
                        </div>
                         <div class="relative z-10 p-4 bg-white">
                            <div class="flex items-center justify-center w-16 h-16 mx-auto bg-indigo-100 text-indigo-700 rounded-full text-2xl font-bold mb-3">2</div>
                            <h4 class="font-bold text-lg">Verify</h4>
                            <p class="text-sm text-stone-600">The compiler's formal system automatically checks each proposal for correctness, rejecting any that violate semantic rules.</p>
                        </div>
                         <div class="relative z-10 p-4 bg-white">
                            <div class="flex items-center justify-center w-16 h-16 mx-auto bg-amber-100 text-amber-700 rounded-full text-2xl font-bold mb-3">3</div>
                            <h4 class="font-bold text-lg">Select</h4>
                            <p class="text-sm text-stone-600">From the set of *verified* options, the human makes the final strategic choice, guided by intuition and LLM analysis.</p>
                        </div>
                    </div>
                    <p class="mt-8 text-stone-600 text-center max-w-3xl mx-auto">
                        This process ensures that human and AI creativity can be applied to hard problems without ever compromising the compiler's mathematical soundness. The "constraint" is that any choice *must* be from the formally validated set, guaranteeing that the system remains in a correct state.
                    </p>
                </div>
            </section>

        </main>
        <footer class="text-center py-8 mt-12 border-t border-stone-200">
            <p class="text-sm text-stone-500">An interactive visualization based on "A Functorial and Grothendieck-Inspired Compiler Architecture".</p>
        </footer>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const data = {
        irDetails: {
            "HLI": { title: "High-Level Intent IR", text: "Articulates human semantic intent using an S-expression grammar. Chosen for its simplicity and homoiconicity (code as data), this is the primary entry point for the developer.", concepts: "Initial Algebras, Functors, Catamorphisms" },
            "DSI": { title: "Domain-Specific Intent IR", text: "Translates general intent into semantic constructs specific to a problem domain (e.g., data processing, scientific computing). It contextualizes the developer's goals.", concepts: "Functors, Sheaves (over domain conceptual sites), Topoi" },
            "LSLI": { title: "Low-Level Scheduling Intent IR", text: "Details the planned computational steps, their sequencing, data dependencies, and potential for parallelism. It forms a blueprint for execution.", concepts: "Categories of Computational Graphs (DAGs), Monads (for sequencing), Applicatives" },
            "HLE": { title: "High-Level Execution IR", text: "An abstract, machine-agnostic execution plan derived from the scheduling intent. It makes execution primitives explicit without committing to specific hardware.", concepts: "Functors, Categorical Abstract Machines (CAM)" },
            "DSE": { title: "Domain-Specific Execution IR", text: "Introduces domain-specific optimizations and code representations, tailoring the execution plan for environments like GPUs or distributed systems.", concepts: "Algebraic Effects & Handlers, Enriched Categories" },
            "LLM_IR": { title: "Low-Level Machine IR", text: "The final IR, representing the program in a form very close to the target language (e.g., Rust/Go) or a backend like LLVM IR. It's the last stop before code generation.", concepts: "Functorial Code Generation, Target Language Categories" }
        },
        toolkit: [
            { name: 'Functor', icon: '→', tagline: 'Structure-preserving map', back: 'Defines transformations between IRs that respect the program\'s structure. Ensures compiler passes are compositional and well-behaved.' },
            { name: 'Profunctor', icon: '↔', tagline: 'Bidirectional lens', back: 'Models two-way mappings between semantics and implementation, allowing them to co-evolve and stay synchronized. Key to refactoring and dynamic feedback.' },
            { name: 'Natural Transformation', icon: '≅', tagline: 'Morphism between functors', back: 'Guarantees semantic consistency. Used to prove that two different compiler passes (e.g., an optimized and unoptimized version) are equivalent.' },
            { name: 'Applicative Functor', icon: '⊞', tagline: 'Composable parallelism', back: 'Represents computations with a static, parallelizable structure. Ideal for independent analysis passes or validating separate modules concurrently.' },
            { name: 'Algebraic Effect', icon: ' effetti', tagline: 'Principled side-effects', back: 'Separates the declaration of effects (like state or errors) from their implementation (handling), making the compiler modular and extensible.' },
            { name: 'Catamorphism', icon: '⊨', tagline: 'Systematic recursion', back: 'A generalized "fold" for processing recursive IRs like ASTs. Used for systematic and verifiable analysis, transformation, and optimization.' },
            { name: 'Sheaf / Topos', icon: '🧩', tagline: 'Structured semantic universe', back: 'Manages context-dependent semantics. A sheaf ensures local information (like types) "glues" together into a consistent global picture. A topos is the universe where this happens.' },
            { name: 'Limit / Colimit', icon: '∀∃', tagline: 'Categorical optimization', back: 'Universal constructions used to formally define optimizations. Limits find common structures (for CSE), and colimits merge structures (for code motion).' },
        ],
        optimizations: {
            "Common Subexpression Elim.": {
                description: "Identify and compute shared subexpressions only once.",
                rationale: "Pullbacks identify shared prerequisite structures leading to a common result. Equalizers find where different computation paths yield the same result.",
                scores: { "Limits/Colimits": 90, "Catamorphisms": 5, "Sheaves/Other": 5 }
            },
            "Constant Folding": {
                description: "Evaluate constant expressions at compile time.",
                rationale: "A catamorphism applies an F-algebra that performs arithmetic on constant parts of a recursive AST.",
                scores: { "Limits/Colimits": 5, "Catamorphisms": 95, "Sheaves/Other": 0 }
            },
            "Dead Code Elimination": {
                description: "Remove code segments that do not affect the program's output.",
                rationale: "Catamorphisms perform reachability/liveness analysis. Liveness can also be modeled as a sheaf property; code is dead if no global section (valid execution trace) depends on it.",
                scores: { "Limits/Colimits": 10, "Catamorphisms": 60, "Sheaves/Other": 30 }
            },
            "Loop Invariant Code Motion": {
                description: "Move computations whose results don't change within a loop, out of the loop.",
                rationale: "Pushouts (a type of colimit) can separate the invariant part from the loop body and re-attach it externally.",
                scores: { "Limits/Colimits": 85, "Catamorphisms": 15, "Sheaves/Other": 0 }
            },
            "Function Inlining": {
                description: "Replace a function call with the actual body of the function.",
                rationale: "Pushouts (a type of colimit) are used for 'gluing' the function body into the call site, universally handling parameter substitution.",
                scores: { "Limits/Colimits": 90, "Catamorphisms": 5, "Sheaves/Other": 5 }
            },
            "SSA Construction": {
                description: "Ensure each variable is assigned only once; use φ-functions at join points.",
                rationale: "φ-functions merge different value definitions. Colimits are the universal way to merge objects based on shared mappings.",
                scores: { "Limits/Colimits": 95, "Catamorphisms": 0, "Sheaves/Other": 5 }
            }
        },
        philosophy: [
            { name: 'Rich Hickey', contribution: 'Emphasizes simplicity, immutable data, and pragmatic complexity management, guiding the IRs to be robust and analyzable.' },
            { name: 'Alexander Grothendieck', contribution: 'His work on topoi and sheaves provides the machinery for deep structural unification and managing complex, context-dependent semantics.' },
            { name: 'Terence Tao', contribution: 'Inspires the need for analytic rigor and formal verification of all transformations, ensuring the compiler\'s soundness.' },
            { name: 'Edward Witten', contribution: 'Encourages finding deep mathematical structures to unify disparate parts of compilation, leading to more elegant and powerful designs.' },
            { name: 'Emmy Noether', contribution: 'Her principle of symmetries preserving invariants provides an analogy: compiler transformations (symmetries) must preserve program semantics (invariants).' }
        ]
    };

    const detailsTitle = document.getElementById('details-title');
    const detailsText = document.getElementById('details-text');
    const detailsExtra = document.getElementById('details-extra');
    const archBoxes = document.querySelectorAll('.arch-box');

    function updateDetails(key) {
        const detail = data.irDetails[key];
        if (detail) {
            detailsTitle.textContent = detail.title;
            detailsText.textContent = detail.text;
            detailsExtra.innerHTML = `<span class="font-semibold">Key Concepts:</span> ${detail.concepts}`;
        }
    }

    function selectArchBox(selectedBox) {
        archBoxes.forEach(b => b.classList.remove('selected'));
        if (selectedBox) {
            selectedBox.classList.add('selected');
        }
    }

    archBoxes.forEach(box => {
        const targetId = box.dataset.id;
        box.addEventListener('mouseenter', () => updateDetails(targetId));
        box.addEventListener('click', (e) => {
            updateDetails(targetId);
            selectArchBox(e.currentTarget);
        });
    });

    const toolkitGrid = document.getElementById('toolkit-grid');
    data.toolkit.forEach(item => {
        const card = document.createElement('div');
        card.className = 'toolkit-card h-48 [perspective:1000px] cursor-pointer group';
        card.innerHTML = `
            <div class="toolkit-card-inner relative w-full h-full">
                <div class="toolkit-card-front absolute w-full h-full bg-white rounded-xl shadow-lg p-6 flex flex-col items-center justify-center text-center">
                    <div class="text-4xl font-serif text-teal-600">${item.icon}</div>
                    <h4 class="text-xl font-bold mt-3">${item.name}</h4>
                    <p class="text-sm text-stone-500 mt-1">${item.tagline}</p>
                </div>
                <div class="toolkit-card-back absolute w-full h-full bg-teal-600 text-white rounded-xl shadow-lg p-6 flex items-center justify-center text-center">
                    <p>${item.back}</p>
                </div>
            </div>
        `;
        card.addEventListener('click', () => {
            card.classList.toggle('is-flipped');
        });
        toolkitGrid.appendChild(card);
    });

    const philosophyGrid = document.getElementById('philosophy-grid');
    data.philosophy.forEach(item => {
        const card = document.createElement('div');
        card.className = 'bg-white p-6 rounded-xl shadow-lg';
        card.innerHTML = `
            <h4 class="text-xl font-bold text-stone-800">${item.name}</h4>
            <p class="mt-2 text-stone-600">${item.contribution}</p>
        `;
        philosophyGrid.appendChild(card);
    });

    const sections = document.querySelectorAll('.content-section');
    const navLinks = document.querySelectorAll('.nav-link');

    function showSection(targetId) {
        sections.forEach(section => {
            section.classList.toggle('active', section.id === targetId);
        });
        navLinks.forEach(link => {
            link.classList.toggle('active', link.dataset.target === targetId);
        });
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const targetId = e.currentTarget.dataset.target;
            showSection(targetId);
            if (targetId === 'optimizations' && !window.optimizationChartInstance) {
                initOptimizationChart();
            }
        });
    });

    showSection('overview');
    const initialBox = document.querySelector('.arch-box[data-id="HLI"]');
    if(initialBox) {
       updateDetails('HLI');
       selectArchBox(initialBox);
    }

    const optimizationSelector = document.getElementById('optimization-selector');
    Object.keys(data.optimizations).forEach(optName => {
        const option = document.createElement('option');
        option.value = optName;
        option.textContent = optName;
        optimizationSelector.appendChild(option);
    });

    function updateOptimizationDetails(optName) {
        const optData = data.optimizations[optName];
        if (!optData) return;

        document.getElementById('opt-title').textContent = optName;
        document.getElementById('opt-desc').textContent = optData.description;
        document.getElementById('opt-rationale').textContent = optData.rationale;

        if (window.optimizationChartInstance) {
            window.optimizationChartInstance.data.datasets[0].data = Object.values(optData.scores);
            window.optimizationChartInstance.update();
        }
    }

    optimizationSelector.addEventListener('change', (e) => {
        updateOptimizationDetails(e.target.value);
    });

    function initOptimizationChart() {
        const ctx = document.getElementById('optimizationChart').getContext('2d');
        const initialOpt = Object.keys(data.optimizations)[0];
        const initialData = data.optimizations[initialOpt];

        window.optimizationChartInstance = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Limits/Colimits', 'Catamorphisms', 'Sheaves/Other'],
                datasets: [{
                    label: 'Relevance',
                    data: Object.values(initialData.scores),
                    backgroundColor: [
                        'rgba(13, 148, 136, 0.6)', // teal-600
                        'rgba(79, 70, 229, 0.6)',  // indigo-600
                        'rgba(168, 162, 158, 0.6)' // stone-400
                    ],
                    borderColor: [
                        '#0d9488',
                        '#4f46e5',
                        '#a8a29e'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: 'y',
                scales: {
                    x: {
                        beginAtZero: true,
                        max: 100,
                        grid: { color: '#e7e5e4' }
                    },
                    y: { grid: { display: false } }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                         callbacks: {
                            label: function(context) {
                                return ` Relevance: ${context.raw}%`;
                            }
                        }
                    }
                }
            }
        });
        updateOptimizationDetails(initialOpt);
    }
});
</script>
</body>
</html>
